import React from 'react'
import {withRouter} from 'react-router-dom'
import {connect} from 'react-redux'
import {Button, Card, Col, Divider, Input, Popconfirm, Row, Select, Switch, Table} from 'antd'
import Screen from "../../../../components/Base/Screen";
import ContentWrap from "../../../../components/Base/ContentWrap";
import styles from './index.module.css';
import Immutable from 'immutable';
import CommonUtil from "../../../../utils/CommonUtil";
import Api from "../../../../configs/Api";

const Option = Select.Option;

class AdminUser extends Screen {
    constructor(props) {
        super(props);

        this.state = {
            columns: [
                {
                    title: '后台用户账号',
                    dataIndex: 'account',
                },
                {
                    title: '姓名',
                    dataIndex: 'nickname',
                },
                {
                    title: '邮箱',
                    dataIndex: 'email',
                },
                {
                    title: '添加时间',
                    dataIndex: 'create_time',
                    render: (text, record, index) => CommonUtil.parseTime(record.create_time),
                },
                {
                    title: '最后登录',
                    dataIndex: 'last_login_time',
                },
                {
                    title: '是否启用',
                    dataIndex: 'is_enable',
                    render: (text, record, index) => (
                        <Switch size={'small'} onChange={async (checked) => {
                            let req = await this.request(Api.USER_SAVE, {
                                id: record.id,
                                is_enable: checked ? 1 : 0,
                                account: record.account
                            });
                            if (req.status !== Api.SUCCESS_CODE) return CommonUtil.toast(req.msg);
                            this.onSetValueToStore(['temp', 'adminUser', 'tableData', index, 'is_enable'], checked);

                        }} checked={!!record.is_enable} disabled={!record.type}/>
                    )
                },
                {
                    title: '操作',
                    dataIndex: '操作',
                    render: (text, record, index) => (
                        <span>
                            <a href="javascript:;"
                               onClick={this.onPushScreen.bind(this, ['/system/admin-user-add', Immutable.fromJS(record)])}>编辑</a>
                            <Divider type="vertical"/>
                            <Popconfirm title="确认删除?" onConfirm={this.onDeleteItem.bind(this, record.id, index)}
                                        okText="是" cancelText="否">
                                <a href="javascript:;">删除</a>
                            </Popconfirm>
                        </span>
                    )
                }
            ],
        }
    }

    async componentDidMount() {
        await this.handleTableChange(this.props.adminUser.get('pagination').toJS());
    }

    onDeleteItem = async (id, index) => {
        let req = await this.request(Api.USER_DELETE, {id: id});
        if (req.status !== Api.SUCCESS_CODE) return CommonUtil.toast(req.msg);
        this.onSetValueToStore(['temp', 'adminUser', 'tableData', index], null, 'deleteIn');
    };

    handleTableChange = async (pagination) => {
        pagination = {...this.props.adminUser.get('pagination').toJS(), ...pagination};

        const pager = {};
        pager.page = pagination.current;
        pager.limit = pagination.pageSize;
        pager.current = pagination.current;
        pager.total = pagination.total;
        pager.pageSize = pager.limit;

        return await this.getTables({
            ...pager
        })
    };

    getTables = async (params = {}) => {
        this.onSetValueToStore(['temp', 'adminUser', 'loading'], true);
        let args = {
            keyword: this.props.adminUser.get('keyword'),
            ...params,
        };
        let req = await this.request(Api.USER_LIST, args);
        this.onSetValueToStore(['temp', 'adminUser', 'loading'], false);
        if (req.status !== Api.SUCCESS_CODE) return CommonUtil.toast(req.msg);
        const pagination = {
            ...params
        };
        pagination.total = req.data.records;
        this.onSetValueToStore(['temp', 'adminUser', 'tableData'], Immutable.fromJS(req.data.rows));
        this.onSetValueToStore(['temp', 'adminUser', 'pagination'], Immutable.fromJS(pagination), "mergeIn");
    };

    render() {
        return (
            <ContentWrap>
                <Card
                    style={{marginTop: '20px', marginBottom: '20px'}}
                >
                    <Row>
                        <Col xs={24} sm={24} md={24} className={styles.formTop}>
                            <Col xs={24} sm={24} md={24} lg={8} className={styles.formTopLeft}>
                                <Input
                                    onChange={e => this.onSetValueToStore(['temp', 'adminUser', 'keyword'], e.target.value)}
                                    value={this.props.adminUser.get('keyword')}
                                    onPressEnter={this.handleTableChange.bind(this, this.props.adminUser.get('pagination').toJS())}
                                    placeholder="账号/姓名" style={{width: '70%'}}/>
                            </Col>
                        </Col>
                    </Row>
                    <Row>
                        <Col xs={24} md={24}>
                            <Button
                                onClick={this.handleTableChange.bind(this, this.props.adminUser.get('pagination'))}
                                type="primary">查询结果</Button>
                        </Col>
                    </Row>
                </Card>

                <Card title={'数据表格'} extra={<div><Button onClick={() => {
                    this.onPushScreen('/system/admin-user-add')
                }} type="primary" style={{marginRight: '10px'}}>添加</Button></div>}>
                    <Row>
                        <Col xs={24} sm={24} md={24}>
                            <Table
                                rowKey={record => record.account}
                                columns={this.state.columns}
                                dataSource={this.props.adminUser.get('tableData').toJS()}
                                pagination={this.props.adminUser.get('pagination').toJS()}
                                loading={this.props.adminUser.get('loading')}
                                onChange={this.handleTableChange.bind(this)}
                                size={'middle'}
                                bordered={true}/>
                        </Col>
                    </Row>
                </Card>
            </ContentWrap>
        )
    }
}

export default withRouter(connect(
    state => ({
        adminUser: state.temp.adminUser,
    })
)(AdminUser))

